package com.ba.base.view.web

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.WindowManager
import android.webkit.JavascriptInterface
import androidx.lifecycle.MutableLiveData
import androidx.multidex.BuildConfig
import com.alibaba.android.arouter.launcher.ARouter
import com.ba.base.api.ApiAuth
import com.ba.base.utils.LogUtils
import com.google.gson.Gson
import com.ba.base.view.net.NetStateChangeReceiver
import com.ba.base.model.vo.UserEntity
import com.ba.base.utils.SharedPreUtils
import com.screx.mcloud.lib.view.dialog.DialogUtils
import qsos.lib.base.utils.ToastUtils

class WebJSInterface(val activity: Activity, private val mHeight: MutableLiveData<Int>) {

    @JavascriptInterface
    fun resize(height: Float) {
        mHeight.postValue((height * activity.resources.displayMetrics.density).toInt())
    }

    @JavascriptInterface
    fun finish() {
        activity.finish()
    }

    @JavascriptInterface
    fun webviewToApp() {
        activity.finish()
    }

    @JavascriptInterface
    fun toast(msg: String? = null) {
        ToastUtils.showToast(activity, msg ?: "")
    }


    @JavascriptInterface
    fun getToken(): String {
        return ApiAuth.getBearerBase()
    }

    @JavascriptInterface
    fun getNetworkStatus(): String {
        return NetStateChangeReceiver.mNetworkType.desc
    }


    @JavascriptInterface
    fun jumpToHome() {
        ARouter.getInstance().build("/app/main").navigation()
        activity.finish()
    }

    @JavascriptInterface
    fun jumpToWeb(title: String?, url: String?) {
        if (TextUtils.isEmpty(url)) {
            ToastUtils.showToast(activity, "跳转连接不存在，跳转失败")
            return
        }
        LogUtils.d("jumpToWeb", "$title   $url")
        ARouter.getInstance().build("/normal/web")
            .withString("title", title)
            .withString("url", url)
            .navigation()
    }
    @JavascriptInterface
    fun jumpToWeb(title: String?, url: String?, rightTitle: String = "", titleUrl: String = "") {
        if (TextUtils.isEmpty(url)) {
            ToastUtils.showToast(activity, "跳转连接不存在，跳转失败")
            return
        }
        LogUtils.d("jumpToWeb", "$title   $url  $rightTitle $titleUrl")
        ARouter.getInstance().build("/normal/web")
            .withString("title", title)
            .withString("url", url)
            .withString("rightTitle", rightTitle)
            .withString("titleUrl", titleUrl)
            .navigation()
    }
    @JavascriptInterface
    fun share(title: String? = null, content: String? = null, url: String? = null) {
        ToastUtils.showToast(activity, "$title $content $url")
    }

    @JavascriptInterface
    fun dialogWithSure(title: String? = null, message: String? = null, action: String? = null) {
        message?.let {
            val mTemMessage = Message()
            mTemMessage.what = 0
            val mBundle = Bundle()
            mBundle.putString("title", title)
            mBundle.putString("message", message)
            mBundle.putString("action", action)
            mTemMessage.data = mBundle
            mHandler.sendMessage(mTemMessage)
        }
    }

    /**
     * 提供画廊效果图片查看
     *
     * @param gallery 为图片信息转为JSON格式后的String数据,转化如下:
     *
     * gallery = List<Image> >>> JSON >>>  [{"content":"图片说明内容,可有可无","url":"图片链接"}]
     * Image = {"content":"图片说明内容,可有可无","url":"图片链接"}
     *
     * 调用代码:    window.android.showInGallery(gallery)
     *
     * 受 JavascriptInterface 限制,大量数据可能无法传递
     * */
    @JavascriptInterface
    fun showInGallery(gallery: String) {
        ARouter.getInstance()
            .build("/home/image/gallery")
            .withString("gallery", "{gallery:$gallery}")
            .navigation()
    }

    @JavascriptInterface
    fun getVersion(): String {
        return BuildConfig.VERSION_NAME
    }

    @JavascriptInterface
    fun getVersionName(): String {
        return BuildConfig.VERSION_NAME
    }

    @JavascriptInterface
    fun getUserInfo(): String {
        var mLoginUser: UserEntity? = null
//        ApiAuth.user?.let {
//            userInfo = Gson().toJson(it)
//        }
        mLoginUser = SharedPreUtils.getUserInfo(activity)
        LogUtils.d("JavascriptInterface", Gson().toJson(mLoginUser))
        return Gson().toJson(mLoginUser)
    }

    @JavascriptInterface
    fun dialogWeb(url: String? = null) {
        url?.let {
            val mTemMessage = Message()
            mTemMessage.what = 1
            val mBundle = Bundle()
            mBundle.putString("url", it)
            mTemMessage.data = mBundle
            mHandler.sendMessage(mTemMessage)
        }
    }

    private val mHandler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                0 -> {
                    val title = msg.data.getString("title")
                    val message = msg.data.getString("message")
                    val action = msg.data.getString("action")
                    message?.let {
                        DialogUtils().sure(activity, title, message, action)
                    }
                }
                1 -> {
                    msg.data.getString("url")?.let {
                        DialogUtils().web(activity, it)
                    }
                }
            }
        }
    }

    // 设置屏幕透明度
    private fun backgroundAlpha(bgAlpha: Float) {
        var lp: WindowManager.LayoutParams = activity?.window!!.attributes
        lp.alpha = bgAlpha// 0.0~1.0
        activity?.window?.attributes = lp //act 是上下文context
    }
}

